package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.reggie.common.BaseContext;
import com.example.reggie.common.R;
import com.example.reggie.entity.ShoppingCart;
import com.example.reggie.service.impl.ShoppingCartServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    ShoppingCartServiceImpl shoppingCartService;

    /**
     * 查看购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看个人的购物车...");
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        //登录后的用户id
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("想要添加的购物车信息:{}",shoppingCart);
        //事务
        ShoppingCart shoppingCartRes=shoppingCartService.saveWithAll(shoppingCart);
        log.info("返回的购物车信息:{}",shoppingCartRes);
        return R.success(shoppingCart);
    }

    /**
     * 清空购物车
     * @param
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(){
        //根据用户id全部删除
        Long userId = BaseContext.getCurrentId();
        log.info("清空购物车的用户id为:{}",userId);
        //delete from shopping_cart where user_id = ? ;
        LambdaQueryWrapper<ShoppingCart>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(userId!=null,ShoppingCart::getUserId,userId);
        boolean remove = shoppingCartService.remove(queryWrapper);
        if (!remove){
            return R.error("清空失败");
        }
        return R.success("清空成功");
    }

    /**
     * 减少购物车
     * @param
     * @return
     */
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        log.info("想要减少的购物车(菜品或者套餐):{}",shoppingCart);
        ShoppingCart shoppingCartRes=shoppingCartService.subWithAll(shoppingCart);
        return R.success(shoppingCartRes);
    }


}
